#!/usr/bin/python2.4
#
# Copyright 2010 Google Inc.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Provides a comparator based on Pareto-efficiency.

Given two instances of Solution, the DominanceComparator
establishes the Pareto-dominance relationship. Solution A
dominates solution B if and only if:
     1) all of objective values of A are at least as good as those of B, and
     2) at least one objective value of A excels that of B
Comparator returns -1 if A dominates B, 0 if neither dominates the other,
and 1 if B dominates A. Note that the optimisation algorithm
is set to minimise objective values, therefore the lesser the better
in this context.
"""

__author__ = 'ntrolls@gmail.com (Shin Yoo)'


class DominanceComparator(object):
  """A comparator based on Pareto-optimality."""

  def Compare(self, a, b):
    """Pareto-optimality comparator; -1 if a dominates b."""
    flag = None
    dominate1 = 0
    dominate2 = 0
    for i in range(len(a.objectives)):
      value1 = a.objectives[i]
      value2 = b.objectives[i]
      if value1 < value2:
        flag = -1
      elif value1 > value2:
        flag = 1
      else:
        flag = 0

      if flag == -1:
        dominate1 = 1
      if flag == 1:
        dominate2 = 1
    if dominate1 == dominate2:
      return 0
    if dominate1 == 1:
      return -1
    return 1
